package org.dce.screencapturer.objects;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.dce.screencapturer.util.ObjectUtils;

@SuppressWarnings("serial")
public class ImageObject 
	extends DrawingObject {

	private BufferedImage image;
	
	private final ResizeHandler resizeHandler = new ResizeHandler(this);
	
	public ImageObject(){
	}
	
	public ImageObject(BufferedImage image){
		setImage(image);
	}
	
	public BufferedImage getImage() {
		return image;
	}

	public void setImage(BufferedImage image) {
		
		BufferedImage oldImage = this.image;
		
		this.image = image;
		
		if (ObjectUtils.equals(oldImage, image)){
			firePropertyChange("image", oldImage, image);
		}
		
		if (image != null){
			setSize(image.getWidth(),image.getHeight());
		}
	}

	@Override
	public void draw(Graphics2D g) {
		
		Rectangle bounds = getBounds();
		
		g.drawImage(
			image, 
			0, 
			0, 
			bounds.width-1, 
			bounds.height-1, 
			this);
	}

	public static ImageObject fromFile(File file) 
		throws IOException{
				
		BufferedImage image = ImageIO.read(file);

		ImageObject imageObject = new ImageObject();
		imageObject.setImage(image);

		return imageObject;
	}

	@Override
	public boolean canDrag(MouseEvent event) {
		return !resizeHandler.isResizeEvent(event);
	}


}
